/* AuthManager.java
 * 
 * Alfred Olschnoegger
 * 26.05.2008
 */

package application;

import java.util.Calendar;
import java.util.Random;

import application.parser.Parser;
import application.parser.StringParser;
import domain.Hunter;
import exceptions.GameEndedException;
import exceptions.GameNotExistingException;
import exceptions.HunterNotRegisteredException;
import exceptions.RabbitBusterException;
import exceptions.UserAlreadyRegisteredException;

/**
 * Manages athentication tasks on the application layer
 * 
 * @date 26.05.2008
 * @author Alfred Olschnoegger
 */

public class AuthManager {

	/**
	 * registers an new user to the given game
	 * 
	 * @param username	name of the user
	 * @param gameID	id of the game where the user wants to register at
	 * @param parse 
	 * @return			parsed key for the client
	 */
	@SuppressWarnings("unchecked")
	public synchronized boolean register(String username, int gameID, Parser parse)  {
		Long key;
		Random rand = new Random();
		try {
			GameInfoProvider prov = new GameInfoProvider(gameID);
			// catching exceptions according the game
			if (prov.containsHunter(username)) {
				throw new UserAlreadyRegisteredException();
			} else {
	
				key = Calendar.getInstance().getTimeInMillis();
				key = key + rand.nextLong();
				key = key % rand.nextLong();
	
				Hunter hunter = new Hunter(username, key);
	
				if (prov.addHunter(hunter)) {
					parse.addAuth(key);
				} else {
					throw new UserAlreadyRegisteredException();
				}
			}
		} catch (RabbitBusterException e) {
			parse.add(e);
			return false;
		}
		return true;
	}

	
	
	public boolean logIn(String username, long key, int gameID, Parser<String> parse) {
		try {
			GameInfoProvider prov = new GameInfoProvider(gameID);
			if (!prov.containsHunter(username)) 
				throw new HunterNotRegisteredException();
			
			if(prov.getHunter(username).isAuthKey(key))
				prov.parse(parse);
			
		} catch (RabbitBusterException e) {
			parse.add(e);
			return false;
		}	
		return true;
	}

}

// end of AuthManager.java
